<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8"/>
    <title>My WebSocket</title>
</head>
<body>
Welcome<br/>
<div>
    登录账号：<input id="loginUserID" type="text"/>
    <button onclick="connect()">登录</button>
</div>
<div>
    发送消息：<input id="text" type="text"/>
</div>
<div>
    发给：<input id="userID" type="text"/>
</div>
<button onclick="send()">发送</button>
<button onclick="closeWebSocket()">关闭连接</button>
<div id="message">
</div>
</body>

<script type="text/javascript">
    var websocket = null;
    var host = "";
    function connect() {
        var serverUrl = "//localhost:8088/WKSP/chat/" + document.getElementById('loginUserID').value;
        if (window.location.protocol == 'http:') {
            host = 'ws:' + serverUrl;
        } else {
            host = 'wss:' + serverUrl;
        }
        //判断当前浏览器是否支持WebSocket
        if ('WebSocket' in window) {
            websocket = new WebSocket(host);
        } else if ('MozWebSocket' in window) {
            websocket = new MozWebSocket(host);
        } else {
            alert("该浏览器不支持WebSocket！");
        }
        //连接发生错误的回调方法
        websocket.onerror = function () {
            setMessageInnerHTML("连接出错");
        };

        //连接成功建立的回调方法
        websocket.onopen = function (event) {
            console.log("连接成功");
            setMessageInnerHTML("已连接服务器！");
        }

        //接收到消息的回调方法
        websocket.onmessage = function (event) {
            console.log(event.data);
            setMessageInnerHTML(event.data);
        }

        //连接关闭的回调方法
        websocket.onclose = function () {
            setMessageInnerHTML("连接关闭");
        }
    }

    //监听窗口关闭事件，当窗口关闭时，主动去关闭websocket连接，防止连接还没断开就关闭窗口，server端会抛异常。
    window.onbeforeunload = function () {
        websocket.close();
    }

    //将消息显示在网页上
    function setMessageInnerHTML(innerHTML) {
        document.getElementById('message').innerHTML += innerHTML + '<br/>';
    }

    //关闭连接
    function closeWebSocket() {
        websocket.close();
    }

    //发送消息
    function send() {
        websocket.send(JSON.stringify({
            message: document.getElementById('text').value,
            to: document.getElementById('userID').value,
        }));
    }
</script>
</html>